package com.business_clean.ui.activity.me;


import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CacheDiskStaticUtils;
import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.CacheDoubleStaticUtils;
import com.blankj.utilcode.util.CleanUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.callback.OnDialogConfirmListener;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.appupdate.AppCheckUpdateUtil;
import com.business_clean.data.mode.appupdate.NewVersionInfo;
import com.business_clean.data.mode.login.UserInfo;
import com.business_clean.databinding.ActivityMyCenterBinding;
import com.business_clean.ui.activity.login.LoginActivity;
import com.business_clean.viewmodel.request.MyCenterViewModel;
import com.idsmanager.doraemonlibrary.DoraemonManager;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

import me.hgj.mvvmhelper.ext.LogExtKt;

public class MyCenterActivity extends BaseActivity<MyCenterViewModel, ActivityMyCenterBinding> {


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        UserInfo userInfo = App.appViewModelInstance.getUserInfo().getValue();
        if (userInfo != null && userInfo.getUser() != null) {
            mDatabind.tvCenterName.setText(userInfo.getUser().getUser_name());
            mDatabind.tvCenterDepartment.setText(userInfo.getUser().getRole_name());
//            mDatabind.tvCenterPost.setText(userInfo.getUser().getJob_name());
            mDatabind.ivCenterAvatar.setAvatar("", userInfo.getUser().getUser_name());
        }

        mDatabind.withAppLogout.setLayoutRadius(0, 0, 10, 10);
        mDatabind.withAppCleanCache.setLayoutRadius(0, 0, 10, 10);


        mDatabind.withAppUpdate.setTvRightText(AppUtils.getAppVersionName());

        mDatabind.withAppCleanCache.setTvRightText((getAllSize()));

        mDatabind.ivCenterAvatar.getAvatarText().setTextSize(18f);

    }


    public String getAllSize() {
        return formatFileSize(getTotalFileSize(FileUtils.getSize(Constant.INTERNAL_LUBAN_PATH))
                + getTotalFileSize((Constant.INTERNAL_MMKV_PATH))
                + getTotalFileSize((Constant.INTERNAL_PHOTO_PATH))
                + getTotalFileSize((Constant.INTERNAL_VIDEO_PATH))
        );
    }

    public long getTotalFileSize(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            return 0; // 如果路径不存在或者不是文件夹，返回大小为0
        }

        long totalSize = 0;
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    totalSize += file.length(); // 累加文件大小
                } else if (file.isDirectory()) {
                    totalSize += getTotalFileSize(file.getAbsolutePath()); // 递归获取子文件夹大小
                }
            }
        }
        return totalSize;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    @Override
    public void onBindViewClick() {


        mDatabind.withAppCleanCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CacheDoubleStaticUtils.clear();
                CacheDiskStaticUtils.clear();
                CacheDiskUtils.getInstance().clear();
                ToastUtil.show("清除中");
                mDatabind.withAppCleanCache.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //删除清空效果
                        CleanUtils.cleanCustomDir(Constant.INTERNAL_LUBAN_PATH);
                        CleanUtils.cleanCustomDir(Constant.INTERNAL_MMKV_PATH);
                        CleanUtils.cleanCustomDir(Constant.INTERNAL_SIGN_HAND_PATH);
                        mDatabind.withAppCleanCache.setTvRightText(getAllSize());
                    }
                }, 1500);
            }
        });

        mDatabind.withAppLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showGeneralDialog(MyCenterActivity.this, "退出登录", "是否退出登录？",
                        "取消", "确定", null, new OnDialogConfirmListener() {
                            @Override
                            public void onConfirm() {
                                //清除所有的内存缓存
                                Glide.get(MyCenterActivity.this).clearMemory();
                                //清楚 token、用户信息、首页数据等，其他的元数据可以保留
                                Constant.ROLE_ID = "";
                                Constant.ROLE_MANGER = false;
                                Constant.ROLE_HR = false;
                                Constant.ROLE_PROJECT_OWNER = false;
                                Constant.ROLE_LEADER = false;
                                Constant.ROLE_CLEANER = false;
                                Constant.ROLE_REGIONAL_MANAGER = false;

                                MMKVHelper.remove(ConstantMMVK.TOKEN);
                                MMKVHelper.remove(ConstantMMVK.USER_INFO);
                                MMKVHelper.remove(ConstantMMVK.INIT_DATA);
                                MMKVHelper.remove(ConstantMMVK.ALL_PROJECT_LIST);
                                MMKVHelper.remove(ConstantMMVK.ROSTER_MENU_STATUS);

                                CommonUtils.restartApp(MyCenterActivity.this);
                            }
                        });
            }
        });


        mDatabind.withAppCleanCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showGeneralDialog(MyCenterActivity.this, "清除缓存", "是否确定清除缓存，清除后无法恢复",
                        "取消", "确定", null, new OnDialogConfirmListener() {
                            @Override
                            public void onConfirm() {
                                FileUtils.deleteFilesInDir(Constant.INTERNAL_PHOTO_PATH);
                                FileUtils.deleteFilesInDir(Constant.INTERNAL_VIDEO_PATH);
                                FileUtils.deleteFilesInDir(Constant.INTERNAL_LUBAN_PATH);
                                FileUtils.deleteFilesInDir(Constant.INTERNAL_MMKV_PATH);
                                mDatabind.withAppCleanCache.setTvRightText((getAllSize()));
                            }
                        });
            }
        });

        //版本更新
        mDatabind.withAppUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewModel.requestCheckApp();
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getNewVersionInfo().observe(this, new Observer<NewVersionInfo>() {
            @Override
            public void onChanged(NewVersionInfo newVersionInfo) {
                //检查是否最新的版本
                if (TextUtils.isEmpty(newVersionInfo.getUrl())) {
                    ToastUtil.show("已经是最新版本了");
                }
                AppCheckUpdateUtil.checkVersionNew(true);
            }
        });
    }
}